package com.tanhua.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/8 19:31
 *
 * 配置鉴权过滤器
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    // 配置不校验得连接
    @Value("${gateway.excludedUrls}")
    private List<String> excludedUrls;

    /**
     * 过滤
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 1.获取当前的连接请求
        String path = exchange.getRequest().getURI().getPath();
        // 2. 放行不需要校验的接口
        // 判断需要放行的集合中没有需要校验的uri
        if(!excludedUrls.contains(path)){
            // 放行
            return chain.filter(exchange);
        }
        // 3. 获取请求头中的token
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        // 4. 后台系统发送的token以 "Bearer" 开头需要处理
        if (!StringUtils.isEmpty(token)){
            // 将它替换掉
            token = token.replaceAll("Bearer ", "");
        }
        // 5. 使用工具类判断token是否有效
        boolean verifyToken = JwtUtils.verifyToken(token);
        // 获取response对象
        ServerHttpResponse response = exchange.getResponse();
        if(!verifyToken){
            Map<String, Object> responseDate = new HashMap<>();
            responseDate.put("errCode", 401);
            responseDate.put("errMessage", "用户未登录");
            return responseError(response, responseDate);
        }
        return chain.filter(exchange);
    }


    //响应错误数据
    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData){
        // 将信息转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try {
            data = objectMapper.writeValueAsBytes(responseData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 输出错误信息到页面
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }





    /**
     * 设置过滤得执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE; // Integerd的最小值
    }
}
